package com.LeeCode;

/**
 * 下降路径最小和
 */

public class Code931 {
    public static void main(String[] args) {
        int[][] grid = {{2, 1, 3}, {6, 5, 4}, {7, 8, 9}};
        System.out.println(new Code931().minFallingPathSum(grid));
    }

    public int minFallingPathSum(int[][] matrix) {
        int n = matrix.length;
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (j == 0) {
                    matrix[i][j] += Math.min(matrix[i - 1][j], matrix[i - 1][j + 1]);
                } else if (j == (n - 1)) {
                    matrix[i][j] += Math.min(matrix[i - 1][j], matrix[i - 1][j - 1]);
                } else {
                    matrix[i][j] += Math.min(matrix[i - 1][j], Math.min(matrix[i - 1][j + 1], matrix[i - 1][j - 1]));
                }
            }
        }
        int ans = Integer.MAX_VALUE;
        for (int i = 0; i < n; i++) {
            ans = Math.min(ans, matrix[n - 1][i]);
        }
        return ans;
    }
}
